package net.medplus.social;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import net.medplus.social.bean.User;
import net.medplus.social.comm.PermissionTools;
import net.medplus.social.databinding.ActivityMainBinding;

import java.util.Locale;
import java.util.Map;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int REQUEST_CODE_PERMISSION_REQUEST = 100;
    /** android6.0权限申请*/
    private PermissionTools mPermissionTools;
    /**友盟shareApi*/
    private UMShareAPI mShareApi;
    /**Data-binding*/
    private ActivityMainBinding binding;
    /**Fresco-用户头像*/
    private SimpleDraweeView mImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(MainActivity.this, R.layout.activity_main);
        mImg = binding.imgMain;
        //权限申请
        permisssionRequest();
    }

    /**
     * 授权
     */
    private void doAuth() {
        mShareApi = UMShareAPI.get(getApplicationContext());
        mShareApi.doOauthVerify(MainActivity.this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                Log.i(TAG, "Authorize success!!");
                //获取用户信息
                getUserInformation();
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                Log.i(TAG, "Authorize error!!!");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                Log.i(TAG, "Authorize cancel!!!");
            }
        });
    }

    /**
     * 删除授权
     */
    private void delAuth() throws Exception {
        if (mShareApi != null) {
            mShareApi.deleteOauth(MainActivity.this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
                @Override
                public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                    Log.i(TAG, "delete Authorize success!!!");
                }

                @Override
                public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                    Log.i(TAG, "delete Authorize error!!!");
                }

                @Override
                public void onCancel(SHARE_MEDIA share_media, int i) {
                    Log.i(TAG, "delete Authorize cancel!!!");
                }
            });
        }else{
            throw new Exception("请先进行授权操作!!!");
        }
    }

    /**
     * 授权成功后获取用户信息
     */
    private void getUserInformation(){
        if (mShareApi != null) {
            mShareApi.getPlatformInfo(MainActivity.this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
                @Override
                public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                    Log.i(TAG, "获取用户信息成功!!!");
                    Set<Map.Entry<String, String>> entries = map.entrySet();
                    StringBuilder sb = new StringBuilder("微信用户信息\r\n");
                    User user = new User();
                    for (Map.Entry<String, String> entry : entries) {
                        String key = entry.getKey();
                        String value = entry.getValue();
                        sb.append(key).append(":").append(value).append("\r\n");
                        if ("nickname".equals(key)) {
                            user.setNickname(value);
                        }
                        if ("headimgurl".equals(key)) {
                            user.setHeadimgurl(value);
                        }
                        if ("sex".equals(key)) {
                            user.setSex("1".equals(value)?"男":"nv");
                        }
                    }
                    String userInfo = sb.toString();
                    user.setAllOriginalData(userInfo);
                    binding.setUser(user);
                    mImg.setImageURI(Uri.parse(user.getHeadimgurl()));
                    Toast.makeText(MainActivity.this, userInfo, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, userInfo);
                }

                @Override
                public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                    Log.i(TAG, String.format(Locale.getDefault(),"获取用户信息失败,状态码:%d,异常信息:%s",i,throwable.getMessage()));
                }

                @Override
                public void onCancel(SHARE_MEDIA share_media, int i) {
                    Log.i(TAG, "取消获取用户信息!!!");
                }
            });
        }
    }

    /**
     * android 6.0 动态权限申请
     */
    private void permisssionRequest() {
        String[] permissionList = new String[]{Manifest.permission.ACCESS_FINE_LOCATION
                ,Manifest.permission.CALL_PHONE
                ,Manifest.permission.READ_LOGS
                ,Manifest.permission.READ_PHONE_STATE
                ,Manifest.permission.WRITE_EXTERNAL_STORAGE
                ,Manifest.permission.SET_DEBUG_APP
                ,Manifest.permission.SYSTEM_ALERT_WINDOW
                ,Manifest.permission.GET_ACCOUNTS};
        mPermissionTools = new PermissionTools(){
            /**处理权限被拒绝的情况*/
            @Override
            public void processForApplyDenied(Activity activity, String[] permissions, int requestCode) {
                for (String p : permissions) {
                    Log.i(TAG, "权限: "+p+" 用户拒绝授予。");
                }
                //Log.i(TAG, "开始重新申请...");
                //重新申请
                //mPermissionTools.permissionRequestForAndroid6_0(activity,permissions,requestCode);
            }
            /**处理所有权限被授予的情况*/
            @Override
            public void processForApplyGranted() {
                Log.i(TAG, "所有权限被授予!!!");
            }
        };
        mPermissionTools.permissionRequestForAndroid6_0(MainActivity.this,permissionList,REQUEST_CODE_PERMISSION_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mShareApi != null) {
            mShareApi.onActivityResult(requestCode,resultCode,data);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mPermissionTools != null) {
            mPermissionTools.processResult(MainActivity.this,requestCode,permissions,grantResults);
        }
    }

    /**登录微信*/
    public void loginWx(View view) {
        //授权
        doAuth();

    }

    /**注销登录*/
    public void logoutWx(View view) {
        //取消授权
        try {
            delAuth();
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}
